// 核心模块主入口 - 提供 SDK 风格的 API
import { BattleCore } from './rpg/BattleCore';
import UserManager from './manage/UserManager';
import MailManage from './manage/MailManage';
import EquipManage from './manage/EquipManage';
import MarketManage from './manage/MarketManage';
import ClientManage from './manage/ClientManage';
import ComponentManage from './manage/ComponentManage';
import SceneManager from './manage/SceneManager';
import Counter from './manage/Counter';
import TaskManage from './manage/TaskManage';
import WorldTaskManage from './manage/WorldTaskManage';
import { RankingService } from '../service/RankingService';
import BuffManager from './rpg/skill/BuffManager';
import EffectManage from './rpg/skill/EffectManage';
import SkillManager from './rpg/skill/SkManager';
import dbInstance from './tool/db';
import xlsxToJson from './tool/xlsxToJson';
import common from './tool/common';
import { baseClass } from './tool/baseClass';
import componentTool from './tool/component';
import { IntentHelper } from './tool/intentHelper';
import { Icard } from './tool/Icard';
import { Icard2 } from './tool/Icard2';
import { baseScene } from './tool/baseScene';
import { deleteImageFromCOS } from './tool/common';
import db from './tool/db';
import { Item } from '../shared/face';
import { managerRegistry } from './manage/BaseManager';
import CounterManager from './manage/CounterManager';
import MailManager from './manage/MailManager';

// 战斗系统SDK
export const rpg = {
    create: () => new BattleCore(),
    BattleCore
};

// 用户管理SDK - 直接导出UserManager
export const user = UserManager;

// 邮件管理SDK - 直接导出MailManage
export const mail = MailManage;

// 道具管理SDK - 通过代理优先走现代化服务
import { createServiceProxy } from '../service/base/LegacyServiceAdapter';
import ModernPropService from '../service/ModernPropService';
import { ModernEquipService } from '../service/ModernEquipService';
import { ModernMarketService } from '../service/ModernMarketService';

// 装备管理SDK - 通过代理优先走现代化服务
const EquipProxy = createServiceProxy(EquipManage as any, ModernEquipService);
export const equip = EquipProxy as typeof EquipManage;
// 直接创建 ModernPropService 代理（不再显式引用 PropManage 标识符）
const PropProxy = createServiceProxy({} as any, ModernPropService);
export const prop = PropProxy as any;

// 市场管理SDK - 通过代理优先走现代化服务
const MarketProxy = createServiceProxy(MarketManage as any, ModernMarketService);
export const market = MarketProxy as typeof MarketManage;


// 任务管理SDK - 直接导出TaskManage
export const task = TaskManage;

// 世界任务管理SDK - 直接导出WorldTaskManage
export const worldTask = WorldTaskManage;

// 排行榜管理SDK - 直接导出RankingService
export const ranking = RankingService;

// 组件管理SDK - 直接导出ComponentManage
export const component = ComponentManage;

// 场景管理SDK - 直接导出SceneManager
export const scene = SceneManager;

// 计数器SDK - 直接导出Counter
export const counter = Counter;

// 技能系统SDK
export const skill = {
    init: () => {
        EffectManage.init();
        BuffManager.init();
        SkillManager.init();
    }
};



export const tool = {
    // 基础工具类
    common: {
        uuid: common.uuid,
        random: (min: number, max: number) => common.random(min, max),
        cover_number: (data: string) => common.cover_number(data),
        randomWeight: (data: { min: number; max: number }) => common.randomWeight(data),
        formatNumberWithLeadingZero: (num: number) => common.formatNumberWithLeadingZero(num),
        countDown: (time: number) => common.countDown(time),
        getCfgAttributeVal: (data: any, key: string) => common.getCfgAttributeVal(data, key),
        timestampToTime: (timestamp: number) => common.timestampToTime(timestamp),
        deleteImageFromCOS: (imageUrl: string) => deleteImageFromCOS(imageUrl)
    },

    // 基础类
    baseClass: {
        create: () => new baseClass()
    },

    // 组件基类
    component: {
        create: () => new componentTool()
    },

    // 场景基类
    baseScene: {
        create: () => new baseScene()
    },

    // 意图助手
    intentHelper: {
        registerIntents: (configs: any[], registerFunc: (mathType: any, command: string, action: Function, self: any, isHideMath?: boolean) => void, self: any) =>
            IntentHelper.registerIntents(configs, registerFunc, self),
        registerButtonIntents: (configs: any[], registerFunc: (mathType: any, command: string, action: Function, self: any, isHideMath?: boolean) => void, self: any, card: any) =>
            IntentHelper.registerButtonIntents(configs, registerFunc, self, card),
        registerSceneIntents: (configs: any[], registerFunc: (mathType: any, command: string, isHideMath: boolean, action: Function, self?: any) => void, self: any) =>
            IntentHelper.registerSceneIntents(configs, registerFunc, self)
    },

    // 卡片工具
    card: {
        create: () => new Icard(),
        create2: () => new Icard2()
    },

    // Excel转JSON工具
    xlsxToJson: {
        init: () => xlsxToJson.init()
    }
};

// 注册管理器到统一管理系统
function registerManagers() {
    // 注册支持BaseManager的管理器
    managerRegistry.register(SceneManager);
    managerRegistry.register(CounterManager);
    managerRegistry.register(MailManager);
    managerRegistry.register(UserManager);
    
    // TODO: 将其他管理器也迁移到BaseManager
    // managerRegistry.register(MailManage);
    // managerRegistry.register(EquipManage);
    // 等等...
}

// 统一的初始化方法
export async function init() {
    await dbInstance.connect();
    await xlsxToJson.init();
    
    // 初始化现代化服务层
    try {
        const { initializeServices } = await import('../service');
        await initializeServices();
        
        // 设置Component的DI容器
        const { container } = await import('../infrastructure/di');
        componentTool.setContainer(container);
        
        console.log('Modern service layer initialized and injected into components');
        
        // 初始化统一错误处理系统（优先级最高）
        try {
            const { initializeUnifiedErrorHandling } = await import('../infrastructure/error/ErrorHandlingInitializer');
            await initializeUnifiedErrorHandling({
                logging: {
                    level: process.env.NODE_ENV === 'production' ? 2 : 1, // INFO : DEBUG
                    enableFileLogging: process.env.NODE_ENV === 'production'
                },
                errorHandler: {
                    hideStackInProduction: true,
                    logAllErrors: true
                }
            });
            console.log('✅ Unified error handling system initialized');
        } catch (errorHandlingError) {
            console.warn('⚠️ Unified error handling initialization failed:', errorHandlingError);
            // 继续执行，保持基本功能
        }
        
        // 初始化统一服务层（新架构）
        try {
            const { initializeUnifiedServices } = await import('../service/UnifiedServiceInitializer');
            await initializeUnifiedServices(container);
            console.log('✅ Unified service layer integration completed');
        } catch (unifiedError) {
            console.warn('⚠️ Unified service layer initialization failed, continuing with existing services:', unifiedError);
            // 不阻止项目启动，继续使用现有服务
        }
        
        // 初始化组件解耦系统（事件驱动架构）
        try {
            const { initializeComponentDecoupling } = await import('../infrastructure/events/ComponentDecouplingInitializer');
            await initializeComponentDecoupling({
                enableEventBus: true,
                enableCompatibilityMode: true,
                eventBus: {
                    debugMode: process.env.NODE_ENV !== 'production',
                    enableMetrics: true
                },
                migration: {
                    strategy: 'gradual',
                    enableRollback: true
                }
            });
            console.log('✅ Component decoupling system initialized');
        } catch (decouplingError) {
            console.warn('⚠️ Component decoupling initialization failed, continuing with existing components:', decouplingError);
            // 不阻止项目启动，继续使用现有组件
        }
        
    } catch (error) {
        console.error('Failed to initialize modern service layer:', error);
        // 继续执行，保持向后兼容
    }
    
    // 注册管理器
    registerManagers();
    
    // 对于已迁移到BaseManager的管理器，使用统一管理
    await managerRegistry.initializeAll();
    
    // 对于尚未迁移的管理器，保持原有初始化方式
    // 由managerRegistry管理Counter与MailManage
    await equip.init();
    // UserManager和SceneManager已由managerRegistry管理，不需要再次初始化
    await ClientManage.init();
    await component.init();
    await skill.init();
    await task.init();
    await worldTask.init();
    await ranking.init();
}

// 统一的保存方法
export async function save() {
    // 使用管理器注册表保存已迁移的管理器
    await managerRegistry.saveAll();
    
    // 保存尚未迁移的管理器
    await market.save();
    await mail.save();
    await counter.save();
    // UserManager已由managerRegistry管理
    await task.save();
    await worldTask.save();
    console.log('save success');
}

// 直接导出所有 manage 类
export {
    UserManager,
    MailManage,
    EquipManage,
    MarketManage,
    ClientManage,
    ComponentManage,
    SceneManager,
    Counter
};

// 导出SDK对象
export const sdk = {
    rpg,
    user,
    mail,
    equip,
    prop,
    market,
    component,
    scene,
    counter,
    skill,
    task,
    worldTask,
    ranking,
    db,
    tool,
    init,
    save
};

export default sdk; 